"use client"

import type React from "react"
import { useState, useEffect, useCallback } from "react"
import { Layout, Menu, Button, Input, Typography, Space, message, Spin, Empty, Modal } from "antd"
import {
  PlusOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  AppstoreOutlined,
  SettingOutlined,
} from "@ant-design/icons"
import type { Host } from "../types"
import HostsGroup from "../components/HostsGroup"
import AddEditHostDialog from "../components/AddEditHostDialog"
import { request } from "../utils/request"

const { Header, Sider, Content } = Layout
const { Search } = Input
const { Title } = Typography

export const HomePage: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false)
  const [categories, setCategories] = useState<string[]>([])
  const [hosts, setHosts] = useState<Host[]>([])
  const [loading, setLoading] = useState(false)
  const [searchText, setSearchText] = useState("")
  const [selectedCategory, setSelectedCategory] = useState<string>("")
  const [addHostDialogOpen, setAddHostDialogOpen] = useState(false)
  const [editingHost, setEditingHost] = useState<Host | null>(null)

  // 获取所有分组
  const fetchCategories = useCallback(async () => {
    try {
      const response = await request.get("/api/categories")
      setCategories(response.data)
      if (response.data.length > 0 && !selectedCategory) {
        setSelectedCategory(response.data[0])
      }
    } catch (error) {
      message.error("获取分组列表失败")
    }
  }, [selectedCategory])

  // 获取主机列表
  const fetchHosts = useCallback(async () => {
    if (!selectedCategory) return

    setLoading(true)
    try {
      const response = await request.get("/api/hosts", {
        params: {
          category: selectedCategory,
          search: searchText,
        },
      })
      setHosts(response.data)
    } catch (error) {
      message.error("获取主机列表失败")
    } finally {
      setLoading(false)
    }
  }, [selectedCategory, searchText])

  useEffect(() => {
    fetchCategories()
  }, [])

  useEffect(() => {
    fetchHosts()
  }, [selectedCategory, searchText])

  // 添加分组
  const handleAddCategory = () => {
    Modal.prompt({
      title: "添加分组",
      content: "请输入分组名称",
      okText: "确定",
      cancelText: "取消",
      onOk: async (value) => {
        if (!value) return
        try {
          await request.post("/api/categories", { name: value })
          message.success("添加分组成功")
          fetchCategories()
        } catch (error) {
          message.error("添加分组失败")
        }
      },
    })
  }

  // 添加/编辑主机
  const handleHostSubmit = async (values: Partial<Host>) => {
    try {
      if (editingHost) {
        await request.put(`/api/hosts/${editingHost.id}`, values)
        message.success("更新主机成功")
      } else {
        await request.post("/api/hosts", {
          ...values,
          category: selectedCategory,
        })
        message.success("添加主机成功")
      }
      setAddHostDialogOpen(false)
      setEditingHost(null)
      fetchHosts()
    } catch (error) {
      message.error("操作失败")
    }
  }

  // 删除主机
  const handleDeleteHost = async (id: string) => {
    try {
      await request.delete(`/api/hosts/${id}`)
      message.success("删除主机成功")
      fetchHosts()
    } catch (error) {
      message.error("删除主机失败")
    }
  }

  // 复制主机
  const handleCopyHost = async (host: Host) => {
    try {
      const { id, ...hostData } = host
      await request.post("/api/hosts", {
        ...hostData,
        title: `${hostData.title} (副本)`,
        category: selectedCategory,
      })
      message.success("复制主机成功")
      fetchHosts()
    } catch (error) {
      message.error("复制主机失败")
    }
  }

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider trigger={null} collapsible collapsed={collapsed} theme="light" width={250}>
        <div style={{ padding: "16px", textAlign: "center" }}>
          <Title level={4} style={{ margin: 0 }}>
            {collapsed ? "Hosts" : "Hosts 管理系统"}
          </Title>
        </div>

        <Menu
          mode="inline"
          selectedKeys={[selectedCategory]}
          items={[
            {
              key: "categories",
              label: "分组列表",
              type: "group",
              children: categories.map((category) => ({
                key: category,
                label: category,
                icon: <AppstoreOutlined />,
                onClick: () => setSelectedCategory(category),
              })),
            },
          ]}
        />

        <div style={{ padding: "16px", textAlign: "center" }}>
          <Button type="dashed" icon={<PlusOutlined />} onClick={handleAddCategory} block>
            {collapsed ? "" : "添加分组"}
          </Button>
        </div>
      </Sider>

      <Layout>
        <Header style={{ padding: "0 16px", background: "#fff" }}>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
            />

            <Space>
              <Search
                placeholder="搜索主机..."
                allowClear
                style={{ width: 300 }}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
              />
              <Button type="primary" icon={<SettingOutlined />} onClick={() => message.info("设置功能开发中")}>
                系统设置
              </Button>
            </Space>
          </div>
        </Header>

        <Content
          style={{
            margin: "24px 16px",
            padding: 24,
            background: "#fff",
            minHeight: 280,
          }}
        >
          <Spin spinning={loading}>
            {selectedCategory ? (
              <HostsGroup
                category={selectedCategory}
                hosts={hosts}
                onAddHost={() => {
                  setEditingHost(null)
                  setAddHostDialogOpen(true)
                }}
                onEditHost={(host) => {
                  setEditingHost(host)
                  setAddHostDialogOpen(true)
                }}
                onDeleteHost={handleDeleteHost}
                onCopyHost={handleCopyHost}
              />
            ) : (
              <Empty description="请选择或添加一个分组" />
            )}
          </Spin>
        </Content>
      </Layout>

      <AddEditHostDialog
        open={addHostDialogOpen}
        editingHost={editingHost}
        categories={categories}
        onClose={() => {
          setAddHostDialogOpen(false)
          setEditingHost(null)
        }}
        onSubmit={handleHostSubmit}
      />
    </Layout>
  )
}

export default HomePage
